#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>
#include <QEventLoop>
#include <QTimer>
#include <QFile>
#include <QIcon>

#include <QDateTime>
#include <QTimeZone>
#include <QString>
#include <QTextStream>


#include <QJsonObject>
#include <QJsonDocument>
#include <QByteArray>

#include <QMessageBox>

#include "httpclient.h"

/*
 *  V1.0.0 2024-08-15 新建
 *  V1.1.0 2024-08-17 远程访问放在公网
 *  V1.2.0 2024-08-22 展示ssh登录指令到文本框
 *  V1.3.0 2024-11-28 支持不同型号设备 （productkey不同）,
 *      V1.3.1 默认AF-HK100 (部分早期环保网关，历史原因，也要选择AF-HK100型号)
 *  V1.4.0 2025-01-17 多人使用，触发启动的bug修复
 *  V1.5.0 2025-03-14 1. 连接/断开平台按钮功能拆分 修复按钮使能bug 2.改为默认ANETIOT_Z
 *
*/

void delay_1(int msec)
{
    QEventLoop loop;//定义一个新的事件循环
    QTimer::singleShot(msec, &loop, SLOT(quit()));//创建单次定时器，槽函数为事件循环的退出函数
    loop.exec();//事件循环开始执行，程序会卡在这里，直到定时时间到，本循环被退出
}

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    mqttClient = nullptr;

    this->setWindowTitle("ANetVPN V1.5.0");
    this->setWindowIcon(QIcon(":/rocket.png"));

    ui->pBtnConn->setStyleSheet("QPushButton { background-color: rgb(188, 188, 188);border-radius: 5px;}"
                          "QPushButton:hover { background-color: green; }"
                          "QPushButton:pressed { background-color: black; }");

    ui->pBtnDisConn->setStyleSheet("QPushButton { background-color: rgb(255, 199, 78);border-radius: 5px;}"
                          "QPushButton:hover { background-color: green; }"
                          "QPushButton:pressed { background-color: black; }");

    ui->btnClear->setStyleSheet("QPushButton { background-color: rgb(188, 188, 188);border-radius: 5px;}"
                          "QPushButton:hover { background-color: green; }"
                          "QPushButton:pressed { background-color: black; }");

    ui->pBtnServiceOn->setStyleSheet("QPushButton { background-color: rgb(231, 255, 231); border-radius: 5px;}"
                          "QPushButton:hover { background-color: green; }"
                          "QPushButton:pressed { background-color: black; }");


    ui->textEdit->ensureCursorVisible();

    ui->btnNormal->setChecked(true);

    m_CurrentAddr = "101.37.151.118";
    m_CurrentProductKey ="MTAxNDM0MTg4NjYyOTk2MTcyOA";// 默认 ANETIOT_Z

    QString clientID;
    qsrand(QTime(0,0,0).msecsTo(QTime::currentTime()));
    clientID = "XYD-CXX"+QString::number(qrand()); //合成 mqtt id
    // clientID = "MQTT_FX_Client";
    qDebug() << "clientID: " << clientID;
    //mqtt 初始化


    // 47.96.11.156 测试
    // 101.37.151.118 正式
    mqttClient = new QMQTT::Client(QHostAddress(m_CurrentAddr), 20071);
    mqttClient->setClientId(clientID); //ClientId 不能重复，不然会覆盖之前连接的人的
    //mqtt 连接成功
    connect(mqttClient,SIGNAL(connected()),this,SLOT(doProcessMqttConnected()));
    //mqtt 退出成功
    connect(mqttClient,SIGNAL(disconnected()),this,SLOT(doProcessMqttDisconnected()));

    //mqtt 订阅成功
    connect(mqttClient,SIGNAL(subscribed(QString)),this,SLOT(doProcessMqttSubscribe(QString)));
    //mqtt 订阅到消息
    connect(mqttClient,SIGNAL(received(QMQTT::Message)),this,SLOT(doProcessMqttReceived(QMQTT::Message)));

    on_pBtnConn_clicked();
}


void MainWindow::doProcessMqttConnected()
{
    // ui->pBtnConn->setText("断开");
    ui->textEdit->append(QDateTime::currentDateTime().toString(Qt::ISODate) +  "<font color=\"#0000FF\"> -- 连接服务器成功 ！--</font> ");

    // mqttClient->subscribe(QString("indicate/server/ODQwODQ3MTgzNzA0Mjg5Mjgw/%1").arg(strInputSN),0);
    // mqttClient->subscribe(QString("indicate/dev/ODQwODQ3MTgzNzA0Mjg5Mjgw/%1").arg(strInputSN),0);

    mqttClient->subscribe(QString("indicate/server/%1/#").arg(m_CurrentProductKey),0);
    mqttClient->subscribe(QString("indicate/dev/%1/#").arg(m_CurrentProductKey),0);

    // ui->pBtnConn->setEnabled(true);
}

void MainWindow::doProcessMqttDisconnected()
{
    // ui->pBtnConn->setText("连接");
    ui->textEdit->append(QDateTime::currentDateTime().toString(Qt::ISODate) +  "<font color=\"#FF0000\"> -- 连接断开！--</font> ");
    ui->textEdit->append(QDateTime::currentDateTime().toString(Qt::ISODate) +  "<font color=\"#FF0000\"> -- 请重新建立连接！--</font> ");

    // ui->pBtnConn->setEnabled(true);
}

void MainWindow::doProcessMqttSubscribe(QString topic)
{
    qDebug() << "topic subscribed : " << topic;
//    QString pText = QString(QDateTime::currentDateTime().toString(Qt::ISODate) +  "<font color=\"#0000FF\"> -- mqtt主题 %1 订阅成功！ --</font> ").arg(topic);
//    ui->textEdit->append(pText);
}

void MainWindow::doProcessMqttReceived(QMQTT::Message msg)
{
    // ui->textEdit->append(msg.topic());
    if(!msg.topic().contains(ui->lineEdit->text()))
    {
        return;
    }

    if(msg.topic().contains("server"))
    {
        ui->textEdit->append("<font color=\"#0000FF\"> -- 唤醒指令发送至网关 ！ --</font> ");
    }
    else
    {
        ui->textEdit->append("<font color=\"#0000FF\"> -- 收到网关响应 ！ --</font> ");
    }

//    QString pTextTopic = QString(QDateTime::currentDateTime().toString(Qt::ISODate) +  "<font color=\"#0000FF\"> -- 主题： %1 ！ --</font> ").arg(msg.topic());
//    ui->textEdit->append(pTextTopic);

//    QString pTextPayload = QString(QDateTime::currentDateTime().toString(Qt::ISODate) +  "<font color=\"#0000FF\"> -- 报文： %1 ！ --</font> ").arg(QString(msg.payload()));
//    ui->textEdit->append(pTextPayload);

    if(!msg.topic().contains("server"))
    {
        startVisitor_FRP();
    }

}

MainWindow::~MainWindow()
{
    if(mqttClient)
    {
        mqttClient->deleteLater();
    }

    delete ui;
}


void MainWindow::on_pBtnConn_clicked()
{

    if(mqttClient->isConnectedToHost())
    {
        QMessageBox::warning(nullptr, "提示", "已连接！");
        return;
    }

    // ui->pBtnConn->setEnabled(false);
    mqttClient->setHost(QHostAddress(m_CurrentAddr));

//    if(ui->pBtnConn->text() == "断开")
//    {
//        mqttClient->disconnectFromHost();
//        return ;
//    }


    // 1-检查本机外网 连通性
    QString networkCmd = "ping 121.43.172.79 -n 2 -w 500";
    QProcess process;
    process.start(networkCmd);
    process.waitForFinished();
    QString result = process.readAll();
    if(!result.contains("TTL="))
    {
        ui->textEdit->append(QDateTime::currentDateTime().toString(Qt::ISODate) +  "<font color=\"#FF0000\"> --- 网络异常！---</font>");
        return ;
    }

    mqttClient->connectToHost();
}


void MainWindow::on_pBtnServiceOn_clicked()
{


    // 0- 检测序列号
    QString strInputSN = ui->lineEdit->text();

    if(strInputSN == "")
    {
        ui->textEdit->append(QDateTime::currentDateTime().toString(Qt::ISODate) +  "<font color=\"#FF0000\"> -- 请先输入网关的序列号! --</font> ");
        return ;
    }

    if(strInputSN.length() != 14)
    {
        ui->textEdit->append(QDateTime::currentDateTime().toString(Qt::ISODate) +  "<font color=\"#FF0000\"> -- 网关序列号格式错误! --</font> ");
        return ;
    }


    if(ui->checkBox_2->checkState() == Qt::Checked)
    {
        startVisitor_FRP();
        return ;
    }

    if(!mqttClient->isConnectedToHost())
    {
        ui->textEdit->append(QDateTime::currentDateTime().toString(Qt::ISODate) +  "<font color=\"#FF0000\"> --- 请先连接到中台！---</font> ");
        return ;
    }


    /*
    {
        "method":"operate",
        "msgid":"874808294606434304",
        "payload":{
            "frpc_status":1
            },
        "sn":"11223344556677",
        "timestamp":1697682160
    }
    */
    // 创建一个空的QJsonObject
    QJsonObject jsonObj;

    // 向QJsonObject添加键值对
    jsonObj["method"] = "operate";
    jsonObj["msgid"] = "874808294606434304";
    jsonObj["sn"] = strInputSN;
    jsonObj["timestamp"] = 1697697138;

    QJsonObject jsonObjPayload;
    jsonObjPayload["frpc_status"] = 1;
    jsonObj["payload"] = jsonObjPayload;

    // 打印JSON对象
//    qDebug() << QJsonDocument(jsonObj).toJson(QJsonDocument::Indented);

    QJsonDocument jsonDoc(jsonObj);
    QByteArray byteArray = jsonDoc.toJson();

    QMQTT::Message msg;
    msg.setTopic(QString("indicate/server/%1/%2").arg(m_CurrentProductKey).arg(strInputSN)); //发布的主题
    //发布的内容,QString 转 QByteArray
    msg.setPayload(byteArray);

    mqttClient->publish(msg);


}


#include <QDesktopServices>

void MainWindow::startVisitor_FRP()
{
    QString strInputSN = ui->lineEdit->text();

    if(strInputSN == "")
    {
        ui->textEdit->append(QDateTime::currentDateTime().toString(Qt::ISODate) +  "<font color=\"#FF0000\"> -- 请先输入网关的序列号! --</font> ");
        return ;
    }

    if(strInputSN.length() != 14)
    {
        ui->textEdit->append(QDateTime::currentDateTime().toString(Qt::ISODate) +  "<font color=\"#FF0000\"> -- 网关序列号格式错误! --</font> ");
        return ;
    }

    // https://frpc.acrel-eem.com/startFrp/
    QString url = API_POST_REQUEST + strInputSN;

    qDebug() << "url --->> "<< url;

    QString response = HttpClient::getInstance()->post(url,5000);

    QByteArray responseBytes = response.toUtf8();
    QJsonDocument responseDoc(QJsonDocument::fromJson(responseBytes));
    QJsonObject responseObject = responseDoc.object();
    qDebug() << "Response:" << responseObject;

    if(!responseObject.contains("data"))
    {
        return;
    }

    QJsonObject data = responseObject["data"].toObject();
    if(!data.contains("res"))
    {
        return;
    }

    // 解析布尔值
    QJsonValue value = data.value("res"); // 获取键为"key"的值
    if (value.isBool()) {
        bool boolValue = value.toBool(); // 将QJsonValue转换为bool

        if(!boolValue) return ;

        if(!data.contains("url"))
        {
            return;
        }

        QJsonValue value = data.value("url"); // 获取键为"key"的值
        if (value.isString()) {
            QString url = value.toString();

            QStringList pItemList = url.split(":");
            if(pItemList.size() == 3)
            {
                qDebug() << "port " << pItemList[2];
                uint port = pItemList.at(2).toUInt();

                QString str = QString("ssh root@121.43.172.79 -oPort=%1").arg(port-1);

                QString textPayload = QString(QDateTime::currentDateTime().toString(Qt::ISODate) +  "<font color=\"#0000FF\"> -- 远程登录： %1</font> ").arg(str);
                ui->textEdit->append(textPayload);

            }

            QString pTextPayload = QString(QDateTime::currentDateTime().toString(Qt::ISODate) +  "<font color=\"#0000FF\"> -- 访问链接： %1</font> ").arg(url);
            // ui->textEdit->append("\n\n");
            ui->textEdit->append(pTextPayload);

            QDesktopServices::openUrl(QUrl(url));
        }


    } else {
        qDebug() << "The value is not a boolean.";
        return ;
    }

}


void MainWindow::on_btnClear_clicked()
{
    ui->textEdit->clear();
}

void MainWindow::on_btnNormal_clicked()
{
    m_CurrentAddr = "101.37.151.118";

    QMessageBox::warning(nullptr, "提示", "服务器切换为正式平台\n请重新连接");
    mqttClient->disconnectFromHost();
}

void MainWindow::on_btnTest_clicked()
{
    m_CurrentAddr = "121.43.38.46";

    // 创建弹框
    QMessageBox::warning(nullptr, "提示", "服务器切换为测试平台\n请重新连接");
    mqttClient->disconnectFromHost();
}

void MainWindow::on_comboBox_activated(const QString &arg1)
{
    if(arg1 == "ANETIOT_Z")
    {
        m_CurrentProductKey = "MTAxNDM0MTg4NjYyOTk2MTcyOA";
        // 创建弹框
        QMessageBox::warning(nullptr, "提示", "设备型号已经修改\n请重新连接");
        mqttClient->disconnectFromHost();
    }
    else if(arg1 == "AF-HK100")
    {
        m_CurrentProductKey = "ODQwODQ3MTgzNzA0Mjg5Mjgw";
        // 创建弹框
        QMessageBox::warning(nullptr, "提示", "设备型号已经修改\n请重新连接");
        mqttClient->disconnectFromHost();
    }

}

void MainWindow::on_pBtnDisConn_clicked()
{
    if(mqttClient->isConnectedToHost())
        mqttClient->disconnectFromHost();
}
